﻿/// <reference path="../../extjs/ext-all-debug.js" />
Ext.define('yzmh.controller.Downloads', {
    extend: 'Ext.app.Controller',

    stores: [ 'Downloads'],

    models: [ 'Download'],

    views: ['download.List'],

    refs: [{
        ref: 'grid',
        selector: 'downloadlist'
    }, {
        ref: 'server',
        selector: 'downloadlist combo[name=server]'
    }, {
        ref: 'comicdata',
        selector: 'downloadlist combo[name=comicdata]'
    }, {
        ref: 'proxy',
        selector: 'downloadlist combo[name=proxy]'
    }],

    init: function () {
        this.control({
            'downloadlist': {
                render: this.loadDownloads
                //itemdblclick: this.showChapterPictures
            },
            'downloadlist button[action=downloadtest]': {
                click: this.downloadTest
            },
            'downloadlist button[action=download]': {
                click: this.downloadChapters
            },
            'downloadlist button[action=complete]': {
                click: this.downloadcomplete
            },
            'downloadlist button[action=editmulti]': {
                click: this.editMulti
            },
            'downloadlist combo[name=proxy]': {
                select: this.proxyCheck
            },
            'downloadlist actioncolumn[action=edit]': {
                click: this.editChapter
            },
            'downloadlist actioncolumn[action=view]': {
                click: this.viewChapter
            }
        });
    },

    proxyCheck: function (combo) {
        Ext.Ajax.request({
            url: 'data/download.aspx?a=proxycheck',
            params: { proxy: combo.getValue() },
            method: 'POST',
            success: function (response, opts) {
                var result = Ext.decode(response.responseText);
                if (result.success) {
                    if (combo.getRawValue().indexOf(result.data.province + "|" + result.data.city + "|" + result.data.isp) != -1) {
                        notification("验证成功", "代理服务器[" + combo.getRawValue() + "]可用！");
                    } else {
                        notification("验证失败", "代理服务器[" + combo.getRawValue() + "]不可用！", true);
                    }
                } else {
                    notification("错误", result.errorMessage, true);
                }
            }
        });
    },

    editMulti: function (button) {
        var rows = this.getGrid().getSelectionModel().getSelection();
        if (rows.length > 0) {
            var ids = [];
            Ext.each(rows, function (row) {
                ids.push(row.get('id'));
            });
            var edit = Ext.create('yzmh.view.chapter.EditMulti').show();
            edit.down("hidden[name=ids]").setValue(ids.join(','));
        }
    },

    viewChapter: function (o, item, rowIndex, colIndex, e, row) {
        window.open("/comic/" + row.get('cid') + "/" + row.get('id') + ".html", '_blank');
    },

    editChapter: function (o, item, rowIndex, colIndex, e, row) {
        Ext.util.Cookies.set("CKFinder:DynamicBaseUrl", row.get('directory') == "" ? this.getComicdata().getRawValue() : row.get('directory'));
        var edit = Ext.create('yzmh.view.chapter.Edit').show();
        edit.down('form').loadRecord(row);
    },
    
    downloadcomplete: function (button) {
        var rows = this.getGrid().getSelectionModel().getSelection(),
            store = this.getDownloadsStore();
        if (rows.length > 0) {
            Ext.Msg.confirm("提示", "确定要把选中的" + rows.length + "个章节标记已完成吗？", function (result) {
                if (result == "yes") {
                    var zjid = [];
                    Ext.each(rows,function(row){
                        zjid.push(row.get("id"));
                    });
                    Ext.Ajax.request({
                        url: 'data/download.aspx?a=downloadcomplete',
                        params: { zjid: zjid.join(',')},
                        method: 'POST',
                        success: function (response, opts) {
                            var result = Ext.decode(response.responseText);
                            if (result.success)
                            {
                                store.reload();
                            } else {
                                Ext.Msg.alert("错误", result.errorMessage);
                            }
                        }
                    });
                }
            });
        }
        
    },

    loadDownloads: function (panel) {
        this.getDownloadsStore().load();
    },

    downloadChapters: function () {
        var rows = this.getGrid().getSelectionModel().getSelection(), 
            store = this.getDownloadsStore(), server = this.getServer().getValue(), comicdata = this.getComicdata().getValue(), proxy = this.getProxy().getValue();
        if (rows.length > 0) {
            var a = [], complete = 0;
            function downloadRow(r, rowIndex) {
                r.set('status','正在下载')
                a.push([0, 0]);
                var urlArr = r.get("tpurl").split('|');
                if (urlArr[a[rowIndex][0]].indexOf('http://') == -1) {
                    urlArr[a[rowIndex][0]] = server + urlArr[a[rowIndex][0]];
                }
                Ext.Ajax.request({
                    url: 'data/download.aspx?a=downloadpic',
                    params: { url: urlArr[a[rowIndex][0]], tpadd: comicdata + r.get("tpadd"), proxy: proxy },
                    method: 'POST',
                    success: function (response, opts) {
                        a[rowIndex][0]++;
                        var result = Ext.decode(response.responseText);
                        if (result.success) {
                            a[rowIndex][1]++;
                            r.set("exist", a[rowIndex][1]);
                            r.set("existper", a[rowIndex][1] / urlArr.length);
                        } else {
                            notification('错误', result.errorMessage, true);
                        }
                        if (a[rowIndex][0] < urlArr.length) {
                            downloadRow(r, rowIndex);
                        }
                        else {
                            r.set('status', '下载结束')
                            complete++;
                            if (complete == rows.length) {
                                var downloaded = [];
                                Ext.each(rows, function (r) {
                                    if (r.get('exist') == r.get('tpurl').split('|').length) {
                                        downloaded.push(r.get('id'));
                                    }
                                });
                                if (downloaded.length > 0) {
                                    Ext.Ajax.request({
                                        url: 'data/download.aspx?a=downloadcomplete',
                                        params: { zjid: downloaded.join(',') },
                                        method: 'POST',
                                        success: function (response, opts) {
                                            var result = Ext.decode(response.responseText);
                                            if (result.success) {
                                                store.reload();
                                            } else {
                                                notification('错误', result.errorMessage, true);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                });
            }
            Ext.Msg.confirm("提示", "确定要下载选中的" + rows.length + "个章节吗？", function (result) {
                if (result == "yes") {
                    Ext.each(rows, downloadRow);
                }
            });
        }
    },

    downloadTest: function () {
        var rows = this.getGrid().getSelectionModel().getSelection(),
            store = this.getDownloadsStore(), server = this.getServer().getValue(), comicdata = this.getComicdata().getValue(), proxy = this.getProxy().getValue();
        if (rows.length == 1) {
            var r = rows[0];
            Ext.Msg.confirm("提示", "确定要测试下载选中的" + rows.length + "个章节吗？", function (result) {
                if (result == "yes") {
                    var urlArr = r.get("tpurl").split('|');
                    if (urlArr[0].indexOf('http://') == -1) {
                        urlArr[0] = server + urlArr[0];
                    }
                    Ext.Ajax.request({
                        url: 'data/download.aspx?a=downloadpic',
                        params: { url: urlArr[0], tpadd: comicdata + r.get("tpadd"), proxy: proxy },
                        method: 'POST',
                        success: function (response, opts) {
                            var result = Ext.decode(response.responseText);
                            if (result.success) {
                                store.reload()
                                notification('提示', "测试成功");
                            } else {
                                notification('错误', result.errorMessage, true);
                            }
                        }
                    });
                }
            });
        }
    }
});
